package com.noah.project.controller

import com.noah.project.global.Const
import com.noah.project.global.JsonManager
import com.noah.project.global.TokenManager
import com.noah.project.dao.AccountDao
import com.noah.project.dao.FriendDao
import com.noah.project.dao.UserDao
import com.noah.project.model.Account
import com.noah.project.model.Friend
import com.noah.project.model.Reply
import com.noah.project.model.User
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class UserApiController {
    @Autowired
    lateinit var userDao: UserDao
    @Autowired
    lateinit var accountDao: AccountDao
    @Autowired
    lateinit var friendDao: FriendDao
    val log = LoggerFactory.getLogger(UserApiController::class.simpleName)
    @RequestMapping(Const.API_REGISTER)
    fun register(account: Account, name: String): Reply {
        try {
            val dbAccount = accountDao.findByUsername(account.username)
            log.info("Register() 是否有这个账号=>" + dbAccount)
            if (dbAccount == null) {
                account.regTime = System.currentTimeMillis()
                val retUid1 = accountDao.insert(account)
                log.info("Register() 插入库=>" + account.toString())
                if (retUid1 > 0) {
                    val user = User(uid = account.uid, name = name)
                    val retUid2 = userDao.insert(user)
                    if (retUid2 > 0) {
                        val retUser = userDao.findById(account.uid);
                        return Reply(code = Const.SUCCESS, msg = "注册成功", data = JsonManager.toJson(retUser))
                    } else {
                        accountDao.delete(retUid1)
                        return Reply(code = Const.FAIL, msg = "注册失败")
                    }
                } else {
                    return Reply(code = Const.FAIL, msg = "注册失败")
                }
            }
            return Reply(code = Const.ERROR_ALREADY, msg = "账号已注册")
        } catch (e: Exception) {
            log.error("注册", e)
            return Reply(code = Const.FAIL_REQUEST, msg = "注册异常")
        }
    }

    @RequestMapping(Const.API_LOGIN)
    fun login(account: Account?, token: String?): Reply {
        try {
            if (token != null) {//使用Token登录
                if (!TokenManager.checkToken(token)) {
                    return Reply(code = Const.FAIL_TOKEN, msg = "Token失效")//超时,Token失效了
                }
                val retUser = userDao.findByToken(token = token)
                if (retUser == null) {
                    return Reply(code = Const.FAIL_TOKEN, msg = "Token失效")//没找到对应的用户,Token失效了
                } else {
                    retUser.token = TokenManager.updateToken(retUser.uid)//更新Token
                    userDao.updateToken(retUser)
                    if (retUser.token != null) {
                        return Reply(code = Const.SUCCESS, msg = "登录成功", data = JsonManager.toJson(retUser))
                    } else {
                        return Reply(code = Const.FAIL_TOKEN, msg = "Token失效")//特殊情况,Token失效了
                    }
                }
            } else {//使用账号密码登录
                val dbAccount = accountDao.findByUsername(account?.username)
                log.info("Login() 是否有这个账号=>" + dbAccount)
                if (dbAccount == null) {//没找到用户,未注册
                    return Reply(code = Const.ERROR_USERNAME, msg = "账号未注册")
                } else {
                    if (account?.password.equals(dbAccount.password)) {//密码正确
                        val retUser = userDao.findById(dbAccount.uid)
                        if (retUser == null) {//找不到用户信息
                            return Reply(code = Const.FAIL, msg = "登录失败")
                        } else {
                            retUser.token = TokenManager.updateToken(retUser.uid);
                            userDao.updateToken(retUser)
                            return Reply(code = Const.SUCCESS, msg = "登录成功", data = JsonManager.toJson(retUser))
                        }
                    } else {//密码错误
                        return Reply(code = Const.ERROR_PASSWORD, msg = "密码错误")
                    }
                }
            }
        } catch (e: Exception) {
            log.error("登录", e)
            return Reply(code = Const.FAIL_REQUEST, msg = "登录异常")
        }
    }

    @RequestMapping(Const.API_UPDATE_ACCOUNT)
    fun updateAccount(account: Account, newPassword: String?, token: String?): Reply {
        try {
            if (!TokenManager.checkToken(token)) {
                return Reply(code = Const.FAIL_TOKEN, msg = "Token失效")
            }
            val dbAccount = accountDao.findById(account.uid)
            if (account.password.equals(dbAccount?.password)) {//密码正确
                log.info("updateAccount() =>" + account.toString() + ",newPassword=" + newPassword)
                account.password = newPassword
                val retUid1 = accountDao.update(account)
                if (retUid1 > 0) {
                    return Reply(code = Const.SUCCESS, msg = "修改密码成功")
                } else {
                    return Reply(code = Const.FAIL, msg = "修改密码失败")
                }
            } else {
                return Reply(code = Const.ERROR_PASSWORD, msg = "原密码错误")
            }
        } catch (e: Exception) {
            log.error("登录", e)
            return Reply(code = Const.FAIL_REQUEST, msg = "修改异常")
        }
    }

    @RequestMapping(Const.API_UPDATE_USER)
    fun update(user: User, token: String?): Reply {
        try {
            if (!TokenManager.checkToken(token)) {
                return Reply(code = Const.FAIL_TOKEN, msg = "Token失效")
            }
            val ret = userDao.update(user)
            if (ret > 0) {
                return Reply(code = Const.SUCCESS, msg = "修改成功", data = JsonManager.toJson(user))
            } else {
                return Reply(code = Const.FAIL, msg = "修改失败")
            }
        } catch (e: Exception) {
            log.error("更新", e)
            return Reply(code = Const.FAIL_REQUEST, msg = "用户异常")
        }
    }

    /*@RequestMapping(Const.API_ALL_USER)
    fun allUser(): Reply {
        try {
            val retUsers = userDao.findAll()
            if (retUsers != null && retUsers.size > 0) {
                return Reply(code = Const.SUCCESS, msg = "获取成功", data = JsonManager.toJson(retUsers))
            }
            return Reply(code = Const.FAIL, msg = "获取失败")
        } catch (e: Exception) {
            log.error("所有用户", e)
            return Reply(code = Const.ERROR_PASSWORD, msg = "用户异常")
        }
    }*///暂时不开放

    @RequestMapping(Const.API_GET_USER)
    fun getUser(uid: Long, token: String?): Reply {
        try {
            if (!TokenManager.checkToken(token)) {
                return Reply(code = Const.FAIL_TOKEN, msg = "Token失效")
            }
            val retUser = userDao.findById(uid = uid)
            if (retUser != null) {
                return Reply(code = Const.SUCCESS, msg = "获取用户成功", data = JsonManager.toJson(retUser))
            }
            return Reply(code = Const.FAIL, msg = "找不到此用户")
        } catch (e: Exception) {
            log.error("单个用户", e)
            return Reply(code = Const.FAIL_REQUEST, msg = "用户异常")
        }
    }

    @RequestMapping(Const.API_FRIEND_RELATION)
    fun friendRelation(friend: Friend, token: String?): Reply {
        try {
            if (!TokenManager.checkToken(token)) {
                return Reply(code = Const.FAIL_TOKEN, msg = "Token失效")
            }
            val retFriend = friendDao.findById(friend)
            if (retFriend != null) {//已经存在好友关系,更新关系
                if (retFriend.relation == Const.FRIEND_BLACK) {
                    return Reply(code = Const.FAIL, msg = "已经拉黑")
                } else {
                    retFriend.relation = friend.relation
                    val ret = friendDao.update(retFriend)
                    if (ret > 0) {
                        return Reply(code = Const.SUCCESS, msg = "成功", data = JsonManager.toJson(retFriend))
                    }
                }
            } else {//不存在好友关系,直接插入
                val ret = friendDao.insert(friend)
                if (ret > 0) {
                    return Reply(code = Const.SUCCESS, msg = "成功", data = JsonManager.toJson(friend))
                }
            }
            return Reply(code = Const.FAIL, msg = "找不到此用户")
        } catch (e: Exception) {
            log.error("单个用户", e)
            return Reply(code = Const.FAIL_REQUEST, msg = "用户异常")
        }
    }

    @RequestMapping(Const.API_GET_FRIEND_LIST)
    fun getFriendList(fid: Long, relation: Int, token: String?): Reply {
        try {
            if (!TokenManager.checkToken(token)) {
                return Reply(code = Const.FAIL_TOKEN, msg = "Token失效")
            }
            val retUser = friendDao.findFriendList(fid, relation)
            if (retUser.isNotEmpty()) {
                return Reply(code = Const.SUCCESS, msg = "获取好友成功", data = JsonManager.toJson(retUser))
            }
            return Reply(code = Const.FAIL, msg = "没有更多好友")
        } catch (e: Exception) {
            log.error("单个用户", e)
            return Reply(code = Const.FAIL_REQUEST, msg = "用户异常")
        }
    }
}